package com.hunter.common.base;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;

/**
 * 控制器基类
 * Created by hunter on 2017/6/5.
 */
public abstract class BaseController {

	private final static Logger _log = LoggerFactory.getLogger(BaseController.class);

	/**
	 * 统一异常处理
	 * @param request
	 * @param response
	 * @param exception
	 */
	@ExceptionHandler
	public void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception exception) {
		_log.error("统一异常处理：", exception);
		outHttpJson(response, new BaseResult(0, "failed", null));
		return;
	}
	
	/**
	 * 更改log日志级别
	 * @param request
	 * @param response
	 * @param l  1:DEBUG 2:INFO 3:WARN 4:ERROR 5:FATAL 6:OFF
	 */
	@RequestMapping(value = "/setLogLevel")
	public void updateLogLevel(HttpServletRequest request, HttpServletResponse response,int l) {
		switch(l){
	        case 1: 
	            l = 10000;
	            break;
	        case 2: 
	        	l = 20000;
	            break;
	        case 3: 
	        	l = 30000;
	            break;
	        case 4: 
	        	l = 40000;
	            break;
	        case 5: 
	        	l = 50000;
	            break;
	        case 6:
	        	l = 2147483647;
	        	break;
	        default: 
	        	l = 10000;
        }
		Level level = Level.toLevel(l); 
		LogManager.getRootLogger().setLevel(level);
	}

	/**
	 * http response输出json
	 * @param obj
	 */
	public void outHttpJson(HttpServletResponse response, Object obj) {
		String outMsg = JSONObject.toJSONString(obj);
		response.setContentType("application/json;charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Max-Age", "3600"); 
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization"); 
		response.setHeader("Access-Control-Allow-Credentials","true");
		outHttpString(response, outMsg);
	}
	
	/**
	 * http response输出String
	 * @param obj
	 */
	public void outHttpString(HttpServletResponse response, Object obj) {
		try {
			response.setCharacterEncoding("utf-8");
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setHeader("Access-Control-Max-Age", "3600"); 
			response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization"); 
			response.setHeader("Access-Control-Allow-Credentials","true");
			PrintWriter out = response.getWriter();
			out.write(String.valueOf(obj).toCharArray());
			out.flush();
		} catch (IOException e) {
		}
	}
	
	public Map getHttpFileRequest(HttpServletRequest request) {
		Map map = new HashMap();
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		List<FileItem> items = new ArrayList();
		try {
			items = upload.parseRequest(request);
			// 得到所有的文件
			Iterator<FileItem> it = items.iterator();
			while (it.hasNext()) {
				FileItem fItem = (FileItem) it.next();
				String fName = "";
				Object fValue = null;
				if (fItem.isFormField()) { // 普通文本框的值
					fName = fItem.getFieldName();
					// fValue = fItem.getString();
					fValue = fItem.getString("UTF-8");
					map.put(fName, fValue);
				} else { // 获取上传文件的值
					fName = fItem.getFieldName();
					fValue = fItem.getInputStream();
					map.put(fName, fValue);
//					String name = fItem.getName();
//					if (name != null && !("".equals(name))) {
//						name = name.substring(name.lastIndexOf(File.separator) + 1);
//					}
				}
			}
		} catch (Exception e) {
			// e.printStackTrace();
			_log.error("读取http请求属性值出错");
		}
		return map;
	}

}
